package com.edu.lxshpc.handler;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.edu.lxshpc.pojo.User;
import com.edu.lxshpc.service.UserService;
import com.edu.lxshpc.utils.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zgh
 * @date 2023/10/28
 * 认证成功处理器
 */
@Component
@Slf4j
public class MySuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private UserService userService;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        log.info("进入自定义登录成功处理器");
        String username = request.getParameter("username");
        User user = new User();
        user.setUsername(username);
        Result result = userService.userLoginByUsername(user);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        String s = JSONUtil.toJsonStr(result);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(s);
    }
}
